<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogShow"
    @close="closeDialog"
  >
    <el-form ref="form" :model="formData" :rules="formRules" label-width="140px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button size="small" @click="dialogShow = false">取消</el-button>
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
      </el-row>
    </el-form>

  </el-dialog>

</template>
<script>
import { addRoleApi, getRoleInfoApi, editRoleApi } from '@/api/setting'
export default {
  data() {
    return {
      dialogShow: false,
      formData: {
        name: '',
        description: ''
      },
      // 定义校验规则
      formRules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '新增'
    }
  },
  methods: {
    async btnOk() {
      try {
        // 1.表单校验
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }

      //   通过formData里面是否有id来判断时新增还是修改
      if (this.formData.id) {
        await editRoleApi(this.formData)
        this.$message.success('修改成功')
      } else {
        // 2.发起请求
        await addRoleApi(this.formData)
        // 3.成功提示
        this.$message.success('新增成功')
      }
      // 4.列表更新 (当前在子组件内，更新列表需要在父组件中操作)
      this.$emit('updateList')
      //   5.关闭弹窗
      this.dialogShow = false
    },
    closeDialog() {
      // 关闭弹窗后，重置表单
      this.formData = {
        name: '',
        description: ''
      }
      //   移除校验
      this.$refs.form.clearValidate()
    },
    // 获取回显数据
    async getRoleInfo(Id) {
      const res = await getRoleInfoApi(Id)
      this.formData = res
      this.dialogShow = true
    }
  }
}
</script>
